import {defineStore} from 'pinia';
import {authService} from '../services/authService';
import {userAPI} from '../services/apiService';
import {router} from "../router/index.js";

export const useUserStore = defineStore('user', {
    state: () => ({
        user: JSON.parse(localStorage.getItem('user') || 'null'),
        token: localStorage.getItem('token') || null,
        isAuthenticated: !!localStorage.getItem('token'),
        favorites: [],
        watchHistory: [],
        ratings: {},
        preferences: {}
    }),

    getters: {
        isLoggedIn: (state) => state.isAuthenticated,
        userInfo: (state) => state.user,
        favoriteMovies: (state) => state.favorites,
        watchHistoryList: (state) => state.watchHistory,
        userRatings: (state) => state.ratings,
        userPreferences: (state) => state.preferences,
        // 检查是否已收藏某部影片
        isFavorite: (state) => (movieId) => {
            return state.favorites.some(fav => fav.movieId === movieId);
        }
    },

    actions: {
        async login(credentials) {
            try {
                const result = await authService.login(credentials);
                // 如果result返回的success不等于true，直接抛出异常
                this.setAuthData(result.user, result.token);
                return result;
            } catch (error) {
                throw error;
            }
        },

        async register(userData) {
            try {
                const result = await authService.register(userData);
                this.setAuthData(result.user, result.token);
                return result;
            } catch (error) {
                throw error;
            }
        },

        async resetPassword(email) {
            try {
                return await authService.resetPassword(email);
            } catch (error) {
                throw error;
            }
        },

        logout() {
            this.user = null;
            this.token = null;
            this.isAuthenticated = false;
            this.favorites = [];
            this.watchHistory = [];
            this.ratings = {};
            this.preferences = {};
            localStorage.removeItem('user');
            localStorage.removeItem('token');
            router.push('/login');
        },

        // 初始化用户数据
        async initUserData() {
            if (!this.isAuthenticated || !this.user) return;

            try {
                // 使用正确的用户ID格式，兼容不同的用户对象结构
                const userId = this.user.id || this.user.userId;
                if (!userId) {
                    console.error('无法获取用户ID');
                    return;
                }

                // 获取用户收藏
                const favorites = await userAPI.getFavorites(userId);
                this.favorites = favorites.data || [];

                // 获取观看历史
                const history = await userAPI.getWatchHistory(userId);
                this.watchHistory = history.data || [];


                // 获取评分
                const ratingsResponse = await userAPI.getRatings(userId);

                // 将评分列表转换为以movieId为key的对象
                const ratingsMap = {};
                if (ratingsResponse.data && Array.isArray(ratingsResponse.data)) {
                    ratingsResponse.data.forEach(rating => {
                        ratingsMap[rating.movieId] = rating;
                    });
                }
                this.ratings = ratingsMap;


                // 获取偏好设置
                if (this.user && this.user.preferences) {
                    this.preferences = {...this.getDefaultPreferences(), ...this.user.preferences};
                }
            } catch (error) {
                console.error('初始化用户数据失败:', error);
            }
        },

        setAuthData(user, token) {
            this.user = user;
            this.token = token;
            this.isAuthenticated = true;
            localStorage.setItem('user', JSON.stringify(user));
            localStorage.setItem('token', token);
        },

        // 获取默认偏好设置
        getDefaultPreferences() {
            return {
                defaultQuality: '1080p',
                subtitleLanguage: 'zh',
                autoPlay: true,
                theme: 'dark'
            };
        },

        async addToFavorites(movie) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.addFavorite(userId, movie.id);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '添加收藏失败');
                }

                this.favorites = [...this.favorites, result.data];

                return result;
            } catch (error) {
                console.error('添加收藏失败:', error);
                throw error;
            }
        },

        async removeFromFavorites(movieId) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.removeFavorite(userId, movieId);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '移除收藏失败');
                }
                this.favorites = this.favorites.filter(fav => fav.movieId !== movieId);
                return result;
            } catch (error) {
                console.error('移除收藏失败:', error);
                throw error;
            }
        },
         async removeBatchFromFavorites(movieIds) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const params = {
                    userId: userId,
                    movieIds: movieIds
                }
        
                const result = await userAPI.removeBatchFavorite(params);
        
                // 过滤掉已移除的收藏
                this.favorites = this.favorites.filter(fav => !movieIds.includes(fav.movieId));
                return result;
            } catch (error) {
                console.error('批量移除收藏失败:', error);
                throw error;
            }
        }
        
        ,

        async addToWatchHistory(movie, watchTime = 0, lastPosition = null) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.addToHistory(userId, movie.id, watchTime, lastPosition);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '添加观看历史失败');
                }
                const existingIndex = this.watchHistory.findIndex(item => item.movieId === movie.id);

                if (existingIndex !== -1) {
                    this.watchHistory[existingIndex].watchTime = watchTime;
                    this.watchHistory[existingIndex].lastPosition = lastPosition;
                    this.watchHistory[existingIndex].lastWatchedAt = new Date();
                } else {
                    this.watchHistory = [...this.watchHistory, result.data];
                }
                return result;
            } catch (error) {
                console.error('添加观看历史失败:', error);
                throw error;
            }
        },

        async removeFromWatchHistory(id) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.deleteHistory(userId, id);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '删除观看记录失败');
                }
                this.watchHistory = this.watchHistory.filter(item => item.id !== id);
                return result;
            } catch (error) {
                console.error('删除观看记录失败:', error);
                throw error;
            }
        },

        async clearWatchHistory() {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.clearHistory(userId);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '清空观看历史失败');
                }
                this.watchHistory = [];
                return result;
            } catch (error) {
                console.error('清空观看历史失败:', error);
                throw error;
            }
        },

        async setRating(movieId, rating, comment = '') {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.setRating(userId, movieId, rating, comment);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '设置评分失败');
                }
                this.ratings[movieId] = {
                    rating,
                    comment,
                    timestamp: Date.now()
                };
                return result;
            } catch (error) {
                console.error('设置评分失败:', error);
                throw error;
            }
        },

        async removeRating(movieId) {
            if (!this.user) throw new Error('用户未登录');

            try {
                const userId = this.user.id || this.user.userId;
                const result = await userAPI.removeRating(userId, movieId);
                // 如果result返回的success不等于true，直接抛出异常
                if (result.success !== true) {
                    throw new Error(result.message || '移除评分失败');
                }
                delete this.ratings[movieId];
                return result;
            } catch (error) {
                console.error('移除评分失败:', error);
                throw error;
            }
        },

        async updatePreferences(newPreferences) {
            if (!this.user) throw new Error('用户未登录');

            try {
                // 使用正确的用户ID格式，后端可能使用不同的字段名
                const userId = this.user.id || this.user.userId;
                const result = await authService.updateProfile(userId, {preferences: newPreferences});
                // 如果result返回的success不等于true，直接抛出异常

                this.preferences = {...this.getDefaultPreferences(), ...this.preferences, ...newPreferences};
                return result;
            } catch (error) {
                console.error('更新偏好设置失败:', error);
                throw error;
            }
        },

        // 初始化偏好设置
        initPreferences() {
            if (Object.keys(this.preferences).length === 0) {
                this.preferences = this.getDefaultPreferences();
                localStorage.setItem('preferences', JSON.stringify(this.preferences));
            }
        }
    }
});